import { useState, useEffect } from "react";

export default function useKeyPress(code) {
  const [keyPress, setKeyPress] = useState(false);

  useEffect(() => {
    const handleKeydown = ({ keyCode }) => {
      if (keyCode === code) {
        setKeyPress(true);
      }
    };
    const handleKeyup = ({ keyCode }) => {
      if (keyCode === code) {
        setKeyPress(false);
      }
    };

    document.addEventListener("keydown", handleKeydown);
    document.addEventListener("keyup", handleKeyup);

    return () => {
      document.removeEventListener("keydown", handleKeydown);
      document.removeEventListener("keyup", handleKeyup);
    };
  }, [code]);

  return keyPress;
}
